package start.demo01.datatype.json.entity.editor.jsonEditor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import start.demo01.datatype.json.interfaces.JSONEditor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static start.demo01.datatype.json.constant.Constant.TIMETYPE;

//时间格式化
public class TimeFormatEditor extends JSONEditor {

    //当前数据类型 变量 目标类型
    //Object insert({ctype,x,dtype},{x,y,c})
    private List<String[]> list;

    public TimeFormatEditor(String args) {
        super(args);
        list=deal();//参数处理
    }
    {
        name="TIMEFORMAT";
    }
    @Override
    protected void operationObject(JSONObject object, String key) {
        return;
    }

    @Override
    protected void operationArray(JSONArray array, int index) {
        return;
    }

    @Override
    protected void operation(JSONObject object) {
        list.forEach(arr -> {
            if(TIMETYPE.equals(arr[0])) {
                Long aLong = object.getLong(arr[1]);
                object.replace(arr[1],time2Format(aLong,arr[2]));
            }else{
                Object trans = trans(arr[0], object.getString(arr[1]), arr[2]);
                object.replace(arr[1],trans);
            }
        });
    }
    public static Object trans(String cFormat,String val,String dType) {
        SimpleDateFormat sdf=new SimpleDateFormat(cFormat);
        Date date;
        try {
            date = sdf.parse(val);
        } catch (ParseException e) {
            System.out.println("time格式化失败");
            return val;
        }
        if(TIMETYPE.equals(dType)) {
            return date.getTime();
        }
        sdf=new SimpleDateFormat(dType);
        return sdf.format(date);
    }
    public static String time2Format(Long time,String format){
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        return sdf.format(time);
    }
}
